<template>
    <div class="role">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>菜单设置</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
           <el-row :gutter="20">
                <el-col :span="8">
                    <div class="grid-content">
                        <div class="add-btn">
                            <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
                        </div>
                        <ul class="role-list">
                            <li :class="roleid == item.id?'active':''" v-for="item in rolesList" @click="getRolesMenu(item.id)">{{item.roleName}}</li>
                        </ul>
                    </div>
                </el-col>
                <el-col :span="16">
                    <div class="grid-content">
                        <div class="save-btn">
                            <el-button type="success" @click="bindRolesMenu()">保存</el-button>
                            <el-button type="primary" @click="pageVisible = true">新增</el-button>
                            <el-button type="danger" @click="removeTree()">删除</el-button>
                        </div>
                        <el-tree
                             v-loading="loading"
                            :data="menuList"
                            default-expand-all
                            show-checkbox
                            node-key="id"
                            ref="tree"
                            :props="defaultProps"
                             @check-change="nodeClick">
                            </el-tree>
                            <!-- @node-click="nodeClick" -->
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-dialog
            title="添加角色"
            :visible.sync="dialogVisible"
            width="400px">
                <el-input v-model="addName" placeholder="请输入角色名称"></el-input>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" >取 消</el-button>
                <el-button type="primary" @click="crerat()">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="添加菜单"
            :visible.sync="pageVisible"
            width="400px">
               <div>
                   <template>
                        <el-radio v-model="radio" label="ONE">一级菜单</el-radio>
                        <el-radio v-model="radio" label="TWO">二级菜单</el-radio>
                    </template>
                    <el-select v-show="radio == 'TWO'" v-model="addForm.Pid" placeholder="请选择父级菜单">
                        <el-option v-for="item in PidList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                    <el-input v-model="addForm.name" placeholder="请输入菜单名称"></el-input>
                    <el-input v-model="addForm.url" placeholder="请输入菜单url"></el-input>
               </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="pageVisible = false" >取 消</el-button>
                <el-button type="primary" @click="addRolesMenu()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { roles  ,creatRole  ,allMenu ,roleMenu ,parMenu ,addMenu } from '../api/api'
// import $ from jquery
export default {
    data() {
        return {
            Token:localStorage.getItem('token'),
            dialogVisible: false,
            defaultProps: {
                children: 'websitePermisssionList',
                label: 'name'
            },
            addName:'',
            rolesList:[],
            roleid:'',
            choosePotene:[],//选中的菜单id
            loading: false,
            myPotenceId:[],//选中角色所绑定的权限
            pageVisible:false,
            menuList:[],
            menuIdList:[],//选中角色所绑定的菜单（包含一级和二级）
            radio:'ONE',
            addForm:{
            },
            PidList:[],//腹肌菜单下拉选项
            deleteId:''//要删除的菜单id
        }
    },
    mounted() {
        this.getRoles();
        this.getList()
        this.getParentMenu()

    },
    methods: {

        nodeClick(menuList, checked){//获取也好删除的id
        if (checked) {
                console.log(menuList.id)
                this.deleteId = menuList.id
            }
        },
        removeTree(){
            let _this = this
            if(_this.deleteId == '' ){
                _this.$message.error('请选择您要删除的菜单');
                return false;
            }
            _this.$confirm('确认删除该菜单?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    _this.$axios.put('permisssion/website/delete/complete?id='+_this.deleteId)
                    .then(function (response) {
                        _this.$message({
                            message: '删除菜单成功',
                            type: 'success'
                        });
                        _this.getList()//刷新
                    })

                }).catch(() => {
                _this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })
        },
        getList(){//获取所有菜单权限
            allMenu().then(res => {
                console.log(res,'获取所有的菜单')
                this.menuList = res.data.content.websitePermisssionList
           })
        },
        getRoles(){//获取角色列表
            this.loading =true
            roles({
                direction: 'DESC',
                propertys:'roleName'
            }).then(res => {
                this.loading =false
                this.rolesList = res.data.content.list
           })
        },
        getRolesMenu(id){//查询-绑定的菜单
            this.roleid = id
            this.loading =true
            let parentId = []//没有二级菜单的被选中的一级菜单
            let childId = []//被选中的二级菜单
            roleMenu({
                roleId:id
            }).then(res => {
                this.loading =false
                  let menuId = res.data.content.websitePermisssionViewList
                if(menuId.length > 0){//角色所绑定的权限不为空
                    this.menuIdList = []//绑定之前先清空
                    for(var i = 0; i<menuId.length ; i++){
                         let Pid = menuId[i].websitePermisssionList

                        if(Pid.length > 0){
                            for(var j = 0; j<Pid.length;j++){
                                let arr = Pid[j].id
                                childId.push(arr)
                            }
                        }else{
                            parentId.push(menuId[i].id)
                        }
                    }
                    this.menuIdList = childId.concat(parentId)
                    this.$refs.tree.setCheckedKeys(this.menuIdList);
                }else{
                    this.menuIdList = []//如果没有绑定权限，清空
                    this.$refs.tree.setCheckedKeys(this.menuIdList);
                }
           })
        },
        bindRolesMenu(){//绑定-菜单
            let _this = this
            if(_this.roleid == ''){
                _this.$message.error('请先选择角色');
                return false;
            }
            _this.choosePotene = []
            _this.choosePotene = _this.$refs.tree.getCheckedKeys().concat(_this.$refs.tree.getHalfCheckedKeys())
            // console.log(_this.$refs.tree.getHalfCheckedKeys())//所有半选中的节点组成的数组
            // console.log(_this.$refs.tree.getCheckedKeys())//所有被选中的节点组成的数组
            console.log(_this.choosePotene)
            if(_this.choosePotene.length == 0){
                _this.$message.error('请选择菜单');
                return false;
            }
            $.ajax({
		        url:_this.$ajaxBase+'role/permisssion/website/relation/multiple?roleId='+_this.roleid,
		        type: 'POST',
		        async: false,
                 headers:{
                        "Access-Token":_this.Token,
                        'Content-Type': 'application/json'
                    },
		        data:JSON.stringify( _this.choosePotene ),
		        success: function (res) {
                    _this.$message({
                        message: '菜单绑定成功',
                        type: 'success'
                    });
		        },
		        error: function (error) {
		            _this.$message.error('菜单绑定失败');
		        }
		    });
        },
        crerat(){//创建角色
            let _this = this
            _this.dialogVisible = false
            _this.$axios.post('role', {
                roleName:_this.addName,
                roleInfo:'系统管理人员'
            })
            .then(function (response) {
                _this.$message({
                    message: '创建角色成功',
                    type: 'success'
                });
                _this.addName = ''
                _this.getRoles()//刷新所有角色
            })
            .catch(function (error) {
                 _this.$message.error('创建角色失败，请稍后再试');
            });

        },
        addRolesMenu(){//新增菜单

            let data
            if(this.radio == 'ONE'){//如果是一级菜单
                data ={
                    name:this.addForm.name,
                    identity:this.addForm.url,
                    type:'ONE'
                }
            }else{
                data ={
                    name:this.addForm.name,
                    identity:this.addForm.url,
                    type:'TWO',
                    websitePermisssion:{
                        id:this.addForm.Pid
                    }
                }
            }

            addMenu(data).then(res => {
                 this.pageVisible = false
                 this.$message({
                    message: '创建菜单成功',
                    type: 'success'
                });
                this.getList()
                this.addForm = {}
           })
        },
        getParentMenu(){//获取父级菜单下拉列表
            parMenu({
                type: 'ONE'
            }).then(res => {
                this.PidList = res.data.content.websitePermisssionList
           })
        }
    },
    computed: {

    }
}

</script>

<style lang='less' scoped>
.message-title{
    cursor: pointer;
}
.handle-row{
    margin-top: 30px;
}
.role-list{
    li{
        height: 40px;
        line-height:40px;
        padding-left: 40px;
        cursor: pointer;
        font-size: 14px;
        transition: all .3s;
        &.active{
            background: #409EFF;
            color: #fff;
        }
        &:hover{
            background: #409EFF;
            opacity: 0.8;
            color: #fff;
        }
    }
}
.role{
    .add-btn{
        margin-bottom: 20px;
        padding-left: 40px;
    }
    .save-btn{
        margin-bottom: 20px;
    }
    .el-select{
        width: 100%;
        margin-top: 20px;
    }
    .el-input{
        margin-top: 20px;
    }
}
</style>

